<template>
  <div>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-resourceType>
          <select-model
            v-model="resourceType"
            @change="changeResourceType"
            type-code="core_resource_type"
          />
        </template>
      </page-filter>
      <div class="select-resource-table">
        <page-table
          :refresh="tableInfo.refresh"
          :init-curpage="tableInfo.initCurpage"
          v-model:ref-obj="tableInfo.ref"
          v-model:data="tableInfo.data"
          :listen-height="false"
          :selectable="selectable"
          :reserveSelection="true"
          :pager="false"
          :query="filterInfo.query"
          :field-list="tableInfo.fieldList"
          :handle="tableInfo.handle"
          :highlight-row="highlightRow"
          :checkedList="tableInfo.checkedList"
          :checkedKey="tableInfo.checkedKey"
          :check-box="checkBox"
          :isRowClickSelect="true"
          @handleEvent="handleEvent"
        />
        <page-table
          ref="cacheResourceTable"
          v-model:data="cacheTableInfo.data"
          :field-list="cacheTableInfo.fieldList"
          :handle="cacheTableInfo.handle"
          :reserveSelection="true"
          :listen-height="false"
          :check-box="false"
          :pager="false"
        />
      </div>
      <template v-slot:dialog-isCascade>
        <el-checkbox
          v-if="selectResourceInfo.fromType === 'dept'"
          v-model="isCascade"
          label="是否级联到下级部门"
          border
        ></el-checkbox>
      </template>
    </page-dialog>
  </div>
</template>

<script setup name="selectResource">
import PageDialog from '../PageDialog/index'
import PageTable from '../DialogTable/index'
import PageFilter from '../PageFilter/index'
import SelectModel from '@/components/SelectModel/index.vue'
import { getDepotAll, getDeptAll, getSupplierAll } from '@/api/core.js'
const emits = defineEmits()
const { proxy } = getCurrentInstance()

const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  showDialog: {
    type: Boolean,
  },
  selectResourceInfo: {
    type: Object,
    default: function () {
      return undefined
    },
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  defaultList: {
    type: Object,
    default: function () {
      return {}
    },
  },
  userResourceDisabledList: {
    type: Array,
    default: function () {
      return []
    },
  },
  fromType: {
    type: String,
    default: '',
  },
})

const isCascade = ref(false)
const resourceType = ref('dept')
// 过滤相关配
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    ...props.query,
    searchType: 'dept',
    keyword: '',
  },
  list: [
    { type: 'slot', label: '资源类型', value: 'resourceType' },
    {
      type: 'input',
      label: '名称/编码',
      value: 'keyword',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  ref: null,
  initCurpage: 1,
  data: [],
  checkedList: [],
  checkedKey: 'id',
  fieldList: [
    { label: '名称', value: 'name' },
    { label: '编码', value: 'code' },
  ],
})
const cacheTableInfo = ref({
  refresh: 1,
  ref: null,
  initCurpage: 1,
  data: [],
  fieldList: [
    { label: '名称', value: 'name' },
    { label: '编码', value: 'code' },
  ],
  handle: {
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: cacheRemove,
        show: true,
        ifRender: function (row) {
          return !row.disabled
        },
      },
      {
        label: '设为默认',
        event: onDefault,
        show: true,
        ifRender: isiFRender,
      },
    ],
  },
})
const checkRowDefault = ref({})
// 弹窗相关
const dialogInfo = ref({
  title: '选择资源',
  btLoading: false,
  width: '58%',
  btList: [
    {
      value: 'isCascade',
      type: 'slot',
    },
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      // disabled: true,
      disabled: false,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref(JSON.parse(JSON.stringify(props.defaultList)))
const tableInfoCopyData = ref([])

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

watch(
  () => props.showDialog,
  (val) => {
    if (val) {
      proxy.$nextTick(() => {
        getList()
      })
    }
  }
)

watch(
  () => tableInfo.value.data,
  (val) => {
    if (val) {
      if (val.length) {
        toggleSelection(tableInfoCopyData.value)
      }
    }
  }
)
// watch(
//   () => cacheTableInfo.value.data,
//   (val) => {
//     if (val) {
//       if (val.length) {
//         const everyBool = val.every(item => {
//           return !item.asDefault
//         })
//       }
//     }
//   }
// )
onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    getList()
    changeResourceType('dept')
    tableInfo.value.data.forEach((item) => {
      if (item.disabled) {
        tableInfo.value.ref?.toggleRowSelection(item)
      }
    })
  })
})

function isiFRender(row) {
  return (
    row.asDefault != '1' &&
    resourceType.value != 'supplier' &&
    resourceType.value != 'dept' &&
    (props.fromType == 'dept' || props.fromType == 'user')
  )
}
// 获取列表
function getList() {
  getDeptAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
      tableInfoCopyData.value = tableInfo.value.data
    }
  })
}
function getDepotList() {
  getDepotAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
      tableInfoCopyData.value = tableInfo.value.data
      let arr = res.data.filter((item) => item.asDefault == '1')
      checkRowDefault.value = arr.length ? arr[0] : {}
    }
  })
}
function getSupplierList() {
  getSupplierAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
      tableInfoCopyData.value = tableInfo.value.data
    }
  })
}
function search() {
  const search = filterInfo.value.query.keyword
  if (search) {
    tableInfo.value.data = tableInfoCopyData.value.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'name') {
          return String(data[key]).indexOf(search) > -1
        }
        if (key === 'supplierName') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
  } else {
    tableInfo.value.data = tableInfoCopyData.value
  }
  if (cacheTableInfo.value.data && cacheTableInfo.value.data.length) {
    tableInfo.value.checkedList = cacheTableInfo.value.data.map((item) => {
      if (resourceType.value === 'supplier') {
        if (item.supplierId) {
          return item.supplierId
        } else {
          return item.id
        }
      } else {
        return item.id
      }
    })
  } else {
    tableInfo.value.checkedList = []
  }
}
function onDefault(row) {
  cacheTableInfo.value.data.map((item) => {
    item.asDefault = undefined
    if (item.id === row.id) {
      item.asDefault = '1'
    }
  })
  tableInfo.value.data.forEach((item) => {
    item.asDefault = undefined
    if (item.id === row.id) {
      item.asDefault = '1'
    }
  })
  tableInfoCopyData.value.forEach((item) => {
    item.asDefault = undefined
    if (item.id === row.id) {
      item.asDefault = '1'
    }
  })
  checkRowDefault.value = row
  selectRow.value[resourceType.value] = cacheTableInfo.value.data
}
function changeResourceType(value) {
  switch (props.selectResourceInfo.subjectType) {
    case 'user':
      filterInfo.value.query.userDefaultDepotId =
        props.selectResourceInfo.subjectId
      break
    case 'dept':
      filterInfo.value.query.deptDefaultDepotId =
        props.selectResourceInfo.subjectId
      break
  }
  if (selectRow.value[value] && selectRow.value[value].length) {
    tableInfo.value.checkedList = selectRow.value[value].map((item) => {
      if (value === 'supplier') {
        if (item.supplierId) {
          return item.supplierId
        } else {
          return item.id
        }
      } else {
        return item.id
      }
    })
  } else {
    tableInfo.value.checkedList = []
  }
  filterInfo.value.query.keyword = ''
  filterInfo.value.query.searchType = value
  filterInfo.value.query.supplier = undefined
  delete filterInfo.value.query.searchField
  tableInfo.value.fieldList = [
    { label: '名称', value: 'name' },
    { label: '编码', value: 'code' },
  ]
  switch (value) {
    case 'supplier':
      filterInfo.value.query.searchType = 'org'
      filterInfo.value.query.supplier = true
      filterInfo.value.query.searchField = 'supplierId'
      tableInfo.value.checkedKey = 'supplierId'
      getSupplierList()
      tableInfo.value.fieldList = [
        { label: '名称', value: 'supplierName' },
        { label: '编码', value: 'supplierCode' },
      ]
      cacheTableInfo.value.fieldList = [
        { label: '名称', value: 'supplierName' },
        { label: '编码', value: 'supplierCode' },
      ]
      // cacheTableInfo.value.handle.btList[1].show = false;

      break
    case 'dept':
      tableInfo.value.checkedKey = 'id'
      tableInfo.value.fieldList = [
        { label: '名称', value: 'name' },
        { label: '编码', value: 'code' },
        { label: '状态', value: 'statusValue' },
      ]
      cacheTableInfo.value.fieldList = [
        { label: '名称', value: 'name' },
        { label: '编码', value: 'code' },
        { label: '状态', value: 'statusValue' },
      ]
      // cacheTableInfo.value.handle.btList[1].show = false;
      delete filterInfo.value.query.supplier
      delete filterInfo.value.query.searchField
      getList()

      break
    case 'depot':
      tableInfo.value.checkedKey = 'id'
      tableInfo.value.fieldList = [
        { label: '名称', value: 'name' },
        { label: '编码', value: 'code' },
        { label: '状态', value: 'statusValue' },
      ]
      cacheTableInfo.value.fieldList = [
        { label: '名称', value: 'name' },
        { label: '编码', value: 'code' },
        { label: '状态', value: 'statusValue' },
      ]
      delete filterInfo.value.query.supplier
      delete filterInfo.value.query.searchField
      getDepotList()
      break
  }
  proxy.$nextTick(() => {
    tableInfo.value.ref?.clearSelection()
    // props.$refs.resourceTable.clearSelection()
  })
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//删除
function cacheRemove(row, index) {
  let rows = cacheTableInfo.value.data
  rows.splice(index, 1)
  let rowArr = []
  rowArr.push(row)
  cancelCheck(rowArr)
  if (row.id === checkRowDefault.value.id) {
    checkRowDefault.value = {}
  }
  cacheTableInfo.value.data = rows
  selectRow.value[resourceType.value] = rows
  if (rows) {
    tableInfo.value.checkedList = rows.map(
      (item) => (tableInfo.value.checkedList[index] = item.id)
    )
  } else {
    tableInfo.value.checkedList = []
  }
}
function save() {
  if (selectRow.value) {
    handleClose()
    emits('callback', selectRow.value, isCascade.value)
  } else {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      showClose: true,
      message: '请选择资源',
    })
  }
}
function handleEvent(event, data, tableData, row) {
  switch (event) {
    case 'tableCheck':
      if (resourceType.value === 'depot') {
        if (data.length) {
          if (checkRowDefault.value && checkRowDefault.value.id) {
            let arr = data.filter(
              (item) => item.id === checkRowDefault.value.id
            )
            if (arr.length) {
              data.forEach((item) => {
                item.asDefault = undefined
                if (item.id === checkRowDefault.value.id) {
                  item.asDefault = '1'
                }
              })
            } else {
              checkRowDefault.value = data[0]
              data[0].asDefault = '1'
            }
          } else {
            data.forEach((item) => {
              item.asDefault = undefined
            })
            data[0].asDefault = '1'
          }
        } else {
          checkRowDefault.value = {}
          tableInfoCopyData.value.forEach((item) => {
            item.asDefault = undefined
          })
          tableInfo.value.data.forEach((item) => {
            item.asDefault = undefined
          })
        }
      }
      selectRow.value[resourceType.value] = data
      cacheTableInfo.value.data = data
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function selectable(row, index) {
  if (row.disabled) {
    return false
  }
  return true
}
//删除时取消勾选
function cancelCheck(val) {
  if (val.length) {
    proxy.$nextTick(() => {
      val.forEach((row) => tableInfo.value.ref?.toggleRowSelection(row, false))
    })
  }
}
function toggleSelection(val) {
  cacheTableInfo.value.data = []
  let rows =
    val.filter(
      (row) =>
        (tableInfo.value.checkedList &&
          tableInfo.value.checkedList.length &&
          tableInfo.value.checkedList.includes(
            row[tableInfo.value.checkedKey]
          )) ||
        row.disabled
    ) || []
  const deepRows = proxy.$fn.deepClone(rows)
  if (rows.length) {
    proxy.$nextTick(() => {
      rows.forEach((row) => tableInfo.value.ref?.toggleRowSelection(row, true))
      cacheTableInfo.value.data.forEach((item, index) => {
        item.asDefault = deepRows[index].asDefault
      })
      cacheTableInfo.value.data = rows
    })
  } else {
    cacheTableInfo.value.data = []
  }
}
</script>

<style scoped lang="scss">
.page-table {
  width: 49%;
  height: 400px;
  .el-dialog__body {
    display: flex;
    flex-direction: column;
  }
}
.el-table--border {
  border-bottom: 1px solid #ebeef5;
}
.select-resource-table {
  display: flex;
  flex-flow: row;
  justify-content: space-between;
  // overflow: hidden;
  height: 400px;
}
</style>
